
int Lx,Ly,Rx,Ry;  //左右摇杆的数值，已Map到（0，255）
int Bl,Br;        //左右按键数值，0-未按，1-按下
String Send = "";
 
void InitRadio();       //初始化遥控器
void ReadJoycon();      //读取各摇杆数据
void SendMessage();     //发送指令


void setup() {
  // put your setup code here, to run once:
  InitRadio();
}

void loop() {
  // put your main code here, to run repeatedly:
  ReadJoycon();
  SendMessage();
  delay(500);
}

void InitRadio()
{
  Serial.begin(9600);
  pinMode(2,INPUT);
  pinMode(3,INPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  for(int i = 4;i <= 11;i = i + 1)
  {
    digitalWrite(i,HIGH);
  }
}

void ReadJoycon()
{
  Bl = digitalRead(2);
  Br = digitalRead(3);
  Lx = analogRead(A1);
  Ly = analogRead(A0);
  Rx = analogRead(A3);
  Ry = analogRead(A2);
  Lx = map(Lx,0,1024,0,255);
  Ly = map(Ly,0,1024,0,255);
  Rx = map(Rx,0,1024,0,255);
  Ry = map(Ry,0,1024,0,255);
  if(Bl == 1)
  {
    digitalWrite(11,HIGH);
  }
  else
  {
    digitalWrite(11,LOW);
  }
  if(Br == 1)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
    digitalWrite(4,LOW);
  }
  if(Bl == 0 && Br == 0)
  {
    Serial.println("#");
  }
}

void SendMessage()
{
  Send = "";
  AddNum(Lx);
  AddNum(Ly);
  AddNum(Rx);
  AddNum(Ry);
  Send = Send + Bl;
  Send = Send + Br;
  //Send = Send + "E";
  Serial.println(Send);
}

void GetSend()
{
  AddNum(Lx);
  AddNum(Ly);
  AddNum(Rx);
  AddNum(Ry);
  Send = Send + Bl;
  Send = Send + Br;
}

void AddNum(int Num)
{
  if(Num <= 9 && Num >= 0)
  {
    Send = Send + "00";
    Send = Send + Num;
  }
  else if(Num <= 99 && Num >= 10)
  {
    Send = Send + "0";
    Send = Send + Num;
  }
  else
  {
    Send = Send + Num;
  }
}
